package com.sitanyun.merchant.guide.push;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.widget.TextView;

import com.google.gson.Gson;
import com.sitanyun.merchant.guide.base.ToastUtil;
import com.sitanyun.merchant.guide.bean.ForgetsmscoedeBean;
import com.sitanyun.merchant.guide.bean.MessagesBean;
import com.sitanyun.merchant.guide.callback.StringCallbacks;
import com.sitanyun.merchant.guide.url.Urls;
import com.sitanyun.merchant.guide.view.activity.SplashsActivity;
import com.sitanyun.merchant.guide.weiht.PhoneUtils;
import com.sitanyun.merchant.guide.weiht.SharedPreferenceUtil;
import com.zhy.http.okhttp.OkHttpUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;
import okhttp3.Call;
import okhttp3.MediaType;

/**
 * Created by jiguang on 17/7/5.
 */

public class OpenClickActivity extends Activity {
    private static final String TAG = "Opens";
    /**消息Id**/
    private static final String KEY_MSGID = "msg_id";
    /**该通知的下发通道**/
    private static final String KEY_WHICH_PUSH_SDK = "rom_type";
    /**通知标题**/
    private static final String KEY_TITLE = "n_title";
    /**通知内容**/
    private static final String KEY_CONTENT = "n_content";
    /**通知附加字段**/
    private static final String KEY_EXTRAS = "n_extras";
    private TextView mTextView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        handleOpenClick();
        Log.e("Opens","onCreate");
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Log.e("Opens","onNewIntent");
        setIntent(intent);
        handleOpenClick();
    }

    /**
     * 处理点击事件，当前启动配置的Activity都是使用
     * Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK
     * 方式启动，只需要在onCreat中调用此方法进行处理
     */
    private void handleOpenClick() {
        Log.d("Opens", "用户点击打开了通知++@#!@3");
      //  ToastUtil.showToast(OpenClickActivity.this,"用户点击打开了通知OpenClickActivity");
        String data = null;
        //获取华为平台附带的jpush信息
        if (getIntent().getData() != null) {
            data = getIntent().getData().toString();
        }

        //获取fcm、oppo、vivo、华硕、小米平台附带的jpush信息
        if (TextUtils.isEmpty(data) && getIntent().getExtras() != null) {
            data = getIntent().getExtras().getString("JMessageExtra");
        }

     //   Log.w(TAG, "msg content is " + String.valueOf(data));
      //  ToastUtil.showToast(OpenClickActivity.this,"用户点击打开了通知OpenClickActivity"+String.valueOf(data));
        if (TextUtils.isEmpty(data))
            return;
        try {
            JSONObject jsonObject = new JSONObject(data);
            String msgId = jsonObject.optString(KEY_MSGID);
            byte whichPushSDK = (byte) jsonObject.optInt(KEY_WHICH_PUSH_SDK);
            String title = jsonObject.optString(KEY_TITLE);
            String content = jsonObject.optString(KEY_CONTENT);
            String string = jsonObject.optString(KEY_EXTRAS);
            Log.e("Opens",msgId+"OpenClickActivity");
            Log.e("Opens",string+"OpenClickActivity");
            try {
                String remark=  new JSONObject(string).getString("remark");
                    MessagesBean testBean=  new Gson().fromJson(remark, MessagesBean.class);
               Log.e("Opens",testBean.getBehavior());
                    if (testBean.getBehavior().equals("CALL")){
                        initcallread(testBean.getNoticeId()+"");
                  PhoneUtils.call(OpenClickActivity.this, testBean.getCPhone());
             Intent intent  = new Intent("android.intent.action.MAIN");
             startActivity(intent);
              }else {
                  Intent i = new Intent(OpenClickActivity.this, SplashsActivity.class);
                  Bundle bundle = new Bundle();
                  //  bundle.putString(JPushInterface.EXTRA_NOTIFICATION_TITLE,message.notificationTitle);
                  bundle.putString(JPushInterface.EXTRA_EXTRA,remark);
                  i.putExtras(bundle);
                  i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP );
                  startActivity(i);
              }

                //
//                Log.e("LOGS",testBean.getBehavior()+"状态");
//                //回电
//                if (testBean.getBehavior().equals("CALL")){
//                    Log.e("LOGS",testBean.getBehavior()+"CALL");
//                    //  PhoneUtils.callPhone(context, testBean.getCPhone());
//                    Intent i = new Intent(context, SplashsActivity.class);
//                    Bundle bundle = new Bundle();
//                  //  bundle.putString(JPushInterface.EXTRA_NOTIFICATION_TITLE,message.notificationTitle);
//                    bundle.putString(JPushInterface.EXTRA_EXTRA,remark);
//                    i.putExtras(bundle);
//                    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP );
//                    context.startActivity(i);
//
////                    context.startActivity(new Intent(context, SplashsActivity.class).putExtra("receiver",testBean)
////                            //  .putExtra("behavior","call")
////                            .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
//                }  //同频
//                else if (testBean.getBehavior().equals("MEETING")){
//                    Log.e("LOGS",testBean.getBehavior()+"MEETING");
//                    //没有超过10秒
//                    //跳转VR
//                    context.startActivity(new Intent(context, SplashsActivity.class).putExtra("cid",testBean)
//                            // .putExtra("behavior","meeting")
//                            .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
//
//
//                } //消息
//                else if (testBean.getBehavior().equals("MESSAGE")){
//                    Log.e("LOGS",testBean.getBehavior()+"MESSAGE");
//                    context.startActivity(new Intent(context, SplashsActivity.class).putExtra("cid",testBean)
//                            //.putExtra("behavior","message")
//                            .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
//                }//浏览
//                else if (testBean.getBehavior().equals("BROWSE")){
//                    Log.e("LOGS",testBean.getBehavior()+"BROWSE");
//                    context.startActivity(new Intent(context, SplashsActivity.class).putExtra("cid",testBean)
//                            //  .putExtra("behavior","browse")
//                            .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
//
//                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            StringBuilder sb = new StringBuilder();
            sb.append("msgId:");
            sb.append(String.valueOf(msgId));
            sb.append("\n");
            sb.append("title:");
            sb.append(String.valueOf(title));
            sb.append("\n");
            sb.append("content:");
            sb.append(String.valueOf(content));
            sb.append("\n");
            sb.append("extras:");
            sb.append(String.valueOf(string));
            sb.append("\n");
            sb.append("platform:");
            sb.append(getPushSDKName(whichPushSDK));
            //上报点击事件
        //   ToastUtil.showToast(OpenClickActivity.this,s);
            JPushInterface.reportNotificationOpened(this, msgId, whichPushSDK);
        } catch (JSONException e) {
            Log.w(TAG, "parse notification error");
            ToastUtil.showToast(OpenClickActivity.this,"parse notification error");

        }
    }

    private void initcallread( String s) {
        Map<String, List> hashMap = new HashMap<>();
        List lists = new ArrayList<>();
        lists.add(s);
        hashMap.put("list", lists);
        OkHttpUtils.postString()
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .addHeader("Content-Type", "application/json")
                .addHeader("Authorization", "Bearer " + SharedPreferenceUtil.getStringData("token"))
                .url(Urls.setIsRead)
                .content(new Gson().toJson(hashMap))
                .build().execute(new StringCallbacks() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) {
                ForgetsmscoedeBean baseEntity = new Gson().fromJson(response, ForgetsmscoedeBean.class);
                if (baseEntity.getCode() == 0) {

                }
            }
        });
    }

    private String getPushSDKName(byte whichPushSDK) {
        String name;
        switch (whichPushSDK) {
            case 0:
                name = "jpush";
                break;
            case 1:
                name = "xiaomi";
                break;
            case 2:
                name = "huawei";
                break;
            case 3:
                name = "meizu";
                break;
            case 4:
                name = "oppo";
                break;
            case 5:
                name = "vivo";
                break;
            case 6:
                name = "asus";
                break;
            case 8:
                name = "fcm";
                break;
            default:
                name = "jpush";
        }
        return name;
    }

}
